﻿using Space.Model.Entity;

namespace Space.Model.Fsm
{
	public class ShipFsm
	{
		private IState<Ship> _previousState;

		public Ship Owner { get; set; }
		public IState<Ship> CurrentState { get; set; }
		public IState<Ship> GlobalState { get; set; }

	    public bool AcceptInput
	    {
            get { return CurrentState.AcceptInput && GlobalState.AcceptInput; }
	    }


	    public ShipFsm(Ship owner)
			: this(owner, new NothingState<Ship>())
		{
		}

		public ShipFsm(Ship owner, IState<Ship> currentState) : this(owner, currentState, new NothingState<Ship>())
		{
		}

		public ShipFsm(Ship owner, IState<Ship> currentState, IState<Ship> globalState )
		{
			Owner = owner;
			CurrentState = currentState;
			GlobalState = globalState;
			_previousState = currentState;
		}

		public void Update(long timestep)
		{
            GlobalState.Execute(timestep);
            CurrentState.Execute(timestep);
		}

		public void Dispose()
		{
		}
		
		public void ChangeState(IState<Ship> newState) 
		{
			_previousState = CurrentState;
			CurrentState.Exit();
			CurrentState = newState;
			CurrentState.Owner = Owner;
			CurrentState.Enter();
		}
		
		public void ChangeGlobalState(IState<Ship> newState)
		{
			GlobalState.Exit();	
			GlobalState = newState;
			GlobalState.Owner = Owner;
			GlobalState.Enter();
		}
		
		public void RevertToPreviousState()
		{
			ChangeState(_previousState);
		}
	}
}
